package com.partner.control;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;










import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.partner.domain.DianZanCollect;
import com.partner.domain.TieZi;
import com.partner.domain.TieZiMessage;
import com.partner.domain.TieZiReply;
import com.partner.response.TieZiResponse;
import com.partner.service.TieZiService;
import com.partner.util.FileUploadUtils;
import com.partner.util.IOUtil;

/**
 * 有关帖子的操作
 * @author Jinshuan
 *
 */
@Controller
public class TieZiAction {

	TieZiService tieZiService = new TieZiService();
	@RequestMapping("/getTieZi")
	public @ResponseBody TieZiResponse getTieZiByFenYe(InputStream io){
		TieZiResponse tieZiResponse = new TieZiResponse();
		//得到传过来的第几页
		String result = IOUtil.inputStreamToStream(io);
		if(result!=null&&!("".equals(result))){
			int pageNow = Integer.parseInt(result);
			tieZiResponse = tieZiService.getTieZi(pageNow, 4);
			
//			System.out.println(tieZiResponse.getTiezis().get(0).getTime());
		}
		return tieZiResponse;
	}
	
	//添加评论
	@RequestMapping("/addReply")
	public @ResponseBody int addReply(InputStream io){
		//得到客户端传来的tieziReply的实体类
		String result = IOUtil.inputStreamToStream(io);
		Gson gson = new Gson();
		TieZiReply tieZiReply = new TieZiReply();
		tieZiReply = gson.fromJson(result, TieZiReply.class);
		
		int return_result = 0;//返回给服务端的
		if(tieZiReply!=null){
			return_result = (tieZiService.insertReply(tieZiReply))+1;
		}
		return return_result;
	}
	
	//删除评论
	@RequestMapping("/deleteReply")
	public @ResponseBody boolean deleteReply(InputStream io){
		System.out.println("删除评论");
		String result = IOUtil.inputStreamToStream(io);
		if(result!=null&&!("".equals(result))){
			int id = Integer.parseInt(result);
			return tieZiService.deleteReply(id);
		}
		return false;
	}
	
	//得到对应用户的点赞和收藏帖子的情况
	@RequestMapping("/getDianZan")
	public @ResponseBody List<DianZanCollect> getDianZanByUser(InputStream io){
		String phone = IOUtil.inputStreamToStream(io);
		Gson gson = new Gson();
		if(phone==null){
			phone = "";
		}
		List<DianZanCollect> dianZanCollects = tieZiService.getDianzan(phone);
//		String result = gson.toJson(dianZanCollects);
//		List<DianZanCollect> dd = (List<DianZanCollect>) gson.fromJson(result, new TypeToken<List<DianZanCollect>>() {}.getType());
//		System.out.println(dd.get(0).getType_tie());
		return dianZanCollects;
	}
	
	//删除某条点赞记录
	@RequestMapping("/deleteZan")
	public @ResponseBody boolean deleteZan(InputStream io){
		String str_dianZanCollect = IOUtil.inputStreamToStream(io);
		
		if(str_dianZanCollect!=null&&!("".equals(str_dianZanCollect))){
			Gson gson = new Gson();
			DianZanCollect dianZanCollect = gson.fromJson(str_dianZanCollect, DianZanCollect.class);
			System.out.println("删除赞");
			return tieZiService.deleteZan(dianZanCollect);
		}else {
			return false;
		}
	}
	
	//增加某条点赞或者收藏的记录，增加时需要将对应的帖子或者评论的赞或者收藏数加1
	@RequestMapping("/setZan")
	public @ResponseBody int setZan(InputStream io){
		String str_dianZanCollect = IOUtil.inputStreamToStream(io);
		if(str_dianZanCollect!=null&&!("".equals(str_dianZanCollect))){
			Gson gson = new Gson();
			DianZanCollect dianZanCollect = gson.fromJson(str_dianZanCollect, DianZanCollect.class);
			int result = tieZiService.insertZanOrCollect(dianZanCollect);
			System.out.println("设置赞111--"+result);
			return result;
		}else{
			return -1;
		}
	}
	
	//查询对应用户的收藏的帖子
	@RequestMapping("/searchShouCangTieZiForUser")
	public @ResponseBody List<TieZi> searchShouCangTieZiForUser(InputStream is){
		String result = IOUtil.inputStreamToStream(is);
		int pageNow = 1;
		String phone = "";
		if(result!=null&&!("".equals(result))){
			String[] res = result.split(";");
			phone = res[0];
			if(res.length>2){
				pageNow = Integer.parseInt(res[1]);
			}
			return tieZiService.selectShouCangTieZiForUser(phone, pageNow, 7);
		}
		return null;
	}
	
	//查询对应用户发出的帖子
	@RequestMapping("/getMyTieZi")
	public @ResponseBody TieZiResponse  getTieZiForUser(InputStream is){
		String result = IOUtil.inputStreamToStream(is);
		List<TieZi> tieZis = null;
		TieZiResponse tieZiResponse = new TieZiResponse();
		if(result!=null&&!("".equals(result))){
				String[] str = result.split(";");
				int pageNow  = Integer.parseInt(str[0]);
				String phone = "";
				if(str.length>1){
					 phone = str[1];
				}
				tieZis = tieZiService.getTieZiForUser(phone, pageNow, 7);
				if(tieZis!=null){
					System.out.println(tieZis.toString());
					tieZiResponse.setCode("2000");
					tieZiResponse.setTiezis(tieZis);
					return tieZiResponse;
				}else{
					tieZis = new ArrayList<TieZi>();
					tieZiResponse.setTiezis(tieZis);
					tieZiResponse.setCode("400");
					tieZiResponse.setDescription("查询出错,稍后再试");
				}
		}
		return tieZiResponse;
	}
	//增加一条帖子记录
	@RequestMapping("/addTiezi")
	public @ResponseBody boolean addTiezi(InputStream is){
		System.out.println("增加帖子");
		String msg = IOUtil.inputStreamToStream(is);
		if(msg!=null&&!("".equals(msg))){
			String[] str_arr = msg.split(";");
			if(str_arr.length==4){
				String phone = str_arr[0];
				String content = str_arr[1];
				String time = str_arr[2];
				String img = str_arr[3];
				System.out.println(msg);
				return tieZiService.addTieZi(phone, content, time,img);
			}
		}
		return false;
	}
	@RequestMapping(value = "/insertTieZi",method = RequestMethod.POST) 
    public boolean processUpload(HttpServletRequest request) {  
		System.out.println("图片***********--");
		String phone = request.getParameter("phone");
		String content = request.getParameter("content");
		String time = request.getParameter("time");
		String img = request.getParameter("filename");
		System.out.println("img--"+img);
//		while(request.getParameterNames().hasMoreElements()){
//			request.getParameterNames().nextElement();
//		}
//		while(request.getAttributeNames().hasMoreElements()){
//			request.getAttributeNames().nextElement();
//		}
		FileUploadUtils.tranferFile(request, "upload/tiezi");
		return tieZiService.addTieZi(phone, content, time,img);
//        model.addAttribute("message", "File '" + file.zgetOriginalFilename() + "' uploaded successfully");  
    } 
	//得到帖子的通知
	@RequestMapping("/getTieZiMsg")
	public @ResponseBody List<TieZiMessage> getTieZiMessage(InputStream is){
		String msg = IOUtil.inputStreamToStream(is);
		System.out.println("帖子信息"+msg);
		if(msg!=null){
			String[] strs = msg.split(";");
			if(strs.length==2){
				return tieZiService.getTieZiMessages(strs[0],Integer.parseInt(strs[1]),8);
			}
		}
		return null;
	}
//	//增加一条帖子记录
//	@RequestMapping("/insertTieZi")
//		public void insertTieZi(InputStream is){
//		System.out.println("转换图片");
////		String webroot = System.getProperty("user.dir");
////		FileUploadUtils.tranferFile(request, webroot);
//		String webroot = System.getProperty("user.dir");
//		 OutputStream out;
//		  int length = 0;  
//	         byte[] buf = new byte[1024];  
//	           
//		try {
//			out = new FileOutputStream(new File(webroot,"pjs11.png"));
//			while((length = is.read(buf))!=-1){  
//			     out.write(buf,0,length);  
//			 }
//			is.close();  
//			out.close();  
//		} catch (Exception e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}  
////         InputStream in = item.getInputStream();  
//           
//       
//  
//		
////		int len = 0;
////		try {
////			System.out.println(is.available()+"--");
////		} catch (IOException e1) {
////			// TODO Auto-generated catch block
////			e1.printStackTrace();
////		}
////		try {
////			byte[] b = new byte[1772];
////			int num = 0;
////			while((len=is.read())!=-1){
////				b[num] = (byte) len;
////				num++;
////			}
////			System.out.println(num);
////			String webroot = System.getProperty("user.dir");
////			System.out.println(webroot);
////			File file = new File(webroot,"pjs2.png");
////			OutputStream out = new FileOutputStream(file);
////			out.write(b);
////			out.close();
////			
////		} catch (IOException e) {
////			// TODO Auto-generated catch block
////			e.printStackTrace();
////		}
//		
//		/******************************************/
//////			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(io);
////		System.out.println("插入帖子");
////			//得到工程的路径
////			String webroot = System.getProperty("user.dir");
////			
////			System.out.println(webroot);
////			try {
////				System.out.println("大小--"+is.available());
////			} catch (IOException e2) {
////				// TODO Auto-generated catch block
////				e2.printStackTrace();
////			}
////			 String sb = new String();  
////		        BufferedReader br = new BufferedReader(new InputStreamReader(is));  
////		        String line = ""; 
////		        String result  = "";
////		        try {
////		        	File file = new File(webroot,"pjs.jpg");
////		        	if(!file.exists()){
////		        		file.createNewFile();
////		        	}
////					FileOutputStream fileOutputStream = new FileOutputStream(file);
////					BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream,"UTF-8"));
////					while ((line = br.readLine()) != null) {  
////						// result = result + line;  
////						sb+=line;
////					}  
////					bufferedWriter.write(sb);
////					bufferedWriter.flush();
////					bufferedWriter.close();
////					br.close();  
////				} catch (Exception e1) {
////					e1.printStackTrace();
////				}finally {  
////		            if (result != null) {  
////		                try {  
////		                    br.close();  
////		                } catch (IOException e) {  
////		                    e.printStackTrace();  
////		                }  
////		            }  
////		        }  
////		        
//		}
	
}
